package com.gec.controller.apply;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gec.entity.ActiveUser;
import com.gec.entity.Employee;
import com.gec.entity.Leavebill;
import com.gec.service.EmployeeService;
import com.gec.service.LeavebillService;
import com.gec.service.workflow.WorkFlowService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author GOF
 * @since 2021-11-17
 */
@Controller
@RequestMapping("/leavebill")
public class LeavebillController {

    @Autowired
    private WorkFlowService wfs;

    @Autowired
    private LeavebillService leavebillService;

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/apply_leavebill")
    public String applyLeaveBill(Model model) {

        model.addAttribute("today", new Date(System.currentTimeMillis()));

        System.out.println(new Date(System.currentTimeMillis()));

        return "apply_leavebill";
    }

    /**
     * 添加请假单,开启请假流程
     *
     * @param leavebill
     * @param user
     * @param leavedate
     * @return
     */
    @RequestMapping(value = "/saveStartLeaveBill", method = RequestMethod.POST)
    public String saveStartLeaveBill(Leavebill leavebill, @SessionAttribute("activeUser") ActiveUser user, String leavedate) {

        //调整时间格式
        leavedate = leavedate.replaceAll("T", " ");
        //设置请假开始时间
        leavebill.setLeaveDate(Timestamp.valueOf(leavedate));
        //设置请假人id
        leavebill.setUserId(user.getId());
        //设置请假状态,1表示审批中
        leavebill.setState(1);

        System.out.println(leavebill);

        //设置流程变量
        Map<String, Object> variable = new HashMap<>();
        variable.put("empId", user.getId() + "_" + user.getUsername());

        //插入新的请假单
        leavebillService.saveOrUpdate(leavebill);

        //开启新的请假流程
        wfs.saveStartProcess("leave", leavebill.getId() + "", variable);


        return "redirect:/leavebill/myLeaveBill";
    }

    /**
     * 当前员工的所有请假单
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/myLeaveBill")
    public String myLeaveBill(@SessionAttribute("activeUser") ActiveUser user, Model model) {

        //查询当前员工的所有请假单
        QueryWrapper<Leavebill> ew = new QueryWrapper<>();
        ew.eq("user_id", user.getId());
        List<Leavebill> leavebills = leavebillService.list2(ew);

        model.addAttribute("leavebills", leavebills);

        return "leaveBill";
    }

    /**
     * 当前员工待办申请单
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/myTaskList")
    public String myTaskList(@SessionAttribute("activeUser") ActiveUser user, Model model) {

        List<Task> tasks = null;

        //查询当前员工的待办任务
        tasks = wfs.findTaskListByName("leave", user.getId() + "_" + user.getUsername());

        if (tasks == null || tasks.size() == 0) {
            //如果查询不到个人任务就查询组任务
            tasks = wfs.findGroupTaskListByName("leave", user.getId() + "_" + user.getUsername());
        }

        model.addAttribute("tasks", tasks);

        model.addAttribute("emp", user);

        return "workflow_task";
    }

    @RequestMapping(value = {"/viewTaskForm/{taskId}"})
    public String viewTaskForm(@PathVariable("taskId") String taskId, Model model) {

        Task task = wfs.findTaskById(taskId);

        //获取请假记录的id,用于查询请假记录
        Integer bizKey = Integer.valueOf(wfs.findBizKeyByTask(task));
        QueryWrapper<Leavebill> ew = new QueryWrapper<>();
        ew.eq("id", bizKey);
        //获取请假记录
        Leavebill leavebill = leavebillService.getOne2(ew);

        //获取批注信息
        List<Comment> comments = wfs.findCommentByBizKey(bizKey + "");

        //获取当前流程的按钮列表
        List<String> outComeBtn = wfs.findOutComeListByTaskId(taskId);

        model.addAttribute("task", task);

        model.addAttribute("leavebill", leavebill);

        model.addAttribute("comments", comments);

        model.addAttribute("outComeBtn", outComeBtn);

        return "approve_leave";
    }

    /**
     * 完成个人任务(任务发起人可能是自己也可能是别人)
     * @param taskId
     * @param id
     * @param comment
     * @param result
     * @param days
     * @return
     */
    @RequestMapping(value = "/submitTask", method = RequestMethod.POST)
    public String submitTask(String taskId, Integer id, @SessionAttribute("activeUser") ActiveUser user, String comment, String result, String days) {

        //取得按钮的值,放入流程变量
        Map<String,Object> variables = new HashMap<>();
        variables.put("result",result);
        variables.put("days",days);

        //完成当前任务,推进到下一流程
        wfs.saveSubmitTask(taskId, user.getId() + "_" + user.getUsername(), result+": "+comment, variables);

        ProcessInstance processInstance = wfs.findProcessInstanceByBizkey("leave", id + "");
        if (processInstance != null) {
            //processInstance不为空,说明该流程未完成

            return "redirect:/leavebill/myLeaveBill";
        }

        //流程完成的话就更改请假单状态
        System.out.println("任务已完成");

        //查询当前任务对应的请假单
        QueryWrapper<Leavebill> ew = new QueryWrapper<>();
        ew.eq("id", id);
        Leavebill leavebill = leavebillService.getOne2(ew);

        //设置状态为审核完成
        leavebill.setState(2);

        //更新字段
        leavebillService.updateById(leavebill);

        return "redirect:/leavebill/myLeaveBill";
    }

    /**
     * 查看审批记录
     */
    @RequestMapping("/viewHisComment/{leaveId}")
    public String viewHisComment(@PathVariable("leaveId") String leaveId, Model model) {

        List<Comment> comments = wfs.findCommentByBizKey(leaveId);

        //查询请假单
        QueryWrapper<Leavebill> ew = new QueryWrapper<>();
        ew.eq("id", Integer.valueOf(leaveId));
        Leavebill leavebill = leavebillService.getOne2(ew);

        model.addAttribute("comments", comments);

        model.addAttribute("isCheck", "check");

        model.addAttribute("leavebill", leavebill);

        return "approve_leave";
    }

    @RequestMapping("/leaveBillAction_delete/{leaveId}")
    public String deleteLeavebill(@PathVariable("leaveId") Integer leaveId) {

        //查询请假单
        QueryWrapper<Leavebill> ew = new QueryWrapper<>();
        ew.eq("id", leaveId);
        Leavebill leavebill = leavebillService.getOne2(ew);

        if (leavebill.getState() == 2) {
            leavebillService.removeById(leavebill.getId());
        }
        return "redirect:/leavebill/myLeaveBill";
    }

    /**
     * 我的待办事务中的查看当前流程图
     *
     * @param taskId
     * @param model
     * @return
     */
    @RequestMapping("/viewCurrentImage/{taskId}")
    public String viewCurrentImage(@PathVariable("taskId") String taskId, Model model) {
        //查询流程部署id和对应的图片名称

        //获取流程定义
        ProcessDefinition definition = wfs.findProcessDefinitionByTaskId(taskId);

        //获取部署id
        String deploymentId = definition.getDeploymentId();

        //获取图片名称
        String imageName = definition.getDiagramResourceName();

        model.addAttribute("deploymentId", deploymentId);
        model.addAttribute("imageName", imageName);

        //找到当前流程的坐标
        List<Map<String, Object>> acs = wfs.findCoordingByBizkey("leave", wfs.findBizKeyByTaskId(taskId), taskId);
        model.addAttribute("acs", acs);

        return "viewimage";
    }

    /**
     * 我的请假单中的查看当前流程图
     *
     * @param leaveId
     * @param model
     * @return
     */
    @RequestMapping("/viewCurrentImageByBill/{leaveId}")
    public String viewCurrentImageByBill(@PathVariable("leaveId") String leaveId, Model model) {
        //查询流程部署id和对应的图片名称

        //通过businesskey获取流程实例
        ProcessInstance processInstance = wfs.findProcessInstanceByBizkey("leave", leaveId);

        //获取流程部署id
        String deploymentId = processInstance.getDeploymentId();

        //获取当前业务对应的任务id
        String taskId = wfs.findTaskByProcessInstId(processInstance.getId()).getId();

        //获取图片名
        String imageName = wfs.findProcessDefinitionByTaskId(taskId).getDiagramResourceName();

        model.addAttribute("deploymentId", deploymentId);

        model.addAttribute("imageName", imageName);

        //找到当前流程的坐标
        List<Map<String, Object>> acs = wfs.findCoordingByBizkey("leave", leaveId, taskId);
        model.addAttribute("acs", acs);

        return "viewimage";
    }

    @RequestMapping("/viewImage/{depId}/{imageName}")
    public String viewImage(@PathVariable("depId") String depId, @PathVariable("imageName") String imageName, HttpServletResponse response) throws IOException {
        //获取图片输入流
        InputStream imageInputStream = wfs.findImageInputStream(depId, imageName);

        //流转换
        IOUtils.copy(imageInputStream, response.getOutputStream());

        //关闭资源
        response.getOutputStream().close();
        imageInputStream.close();
        return null;
    }
}

